package cn.px.rest.controller.upms;

import cn.hutool.core.date.DateUtil;
import cn.px.common.constant.CommonConstants;
import cn.px.common.enums.ResultCode;
import cn.px.common.exception.BusinessException;
import cn.px.common.util.FileUtils;
import cn.px.common.util.IdGeneratorUtils;
import cn.px.common.util.R;
import cn.px.common.util.excel.ExcelToHtml;
import cn.px.dao.dto.upms.SysExcelImportDTO;
import cn.px.dao.entity.upms.SysExcelImport;
import cn.px.service.upms.SysExcelImportService;
import cn.px.dao.util.ExcelUtil;
import cn.px.dao.vo.export.upms.ExportSysExcelImportVO;
import cn.px.common.util.BeanConverterUtil;
import cn.px.common.validation.group.AddGroup;
import cn.px.common.validation.group.UpdateGroup;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.rest.log.annotation.SysLog;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description excel导入 控制器
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2019,北京乾元坤和科技有限公司 All rights reserved.
 */
@RestController
@RequestMapping("/upms/excel-imports")
public class SysExcelImportController {

    @Autowired
    private SysExcelImportService sysExcelImportService;

    private static final String XSSF = ".xlsx";

    @Value("${upload.root-dir}")
    private String UPLOAD_ROOT_FOLDER;

    /**
     * 通过id查询单条记录
     *
     * @param id 主键
     * @return R
     */
    @GetMapping("/{id}")
    public R<SysExcelImport> getById(@PathVariable("id") String id) {
        return new R<>(sysExcelImportService.getModelById(id));
    }

    /**
     * 新增记录
     *
     * @param sysExcelImportDTO excel导入DTO
     * @return R
     */
    @SysLog("新增excel导入")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('upms-excel-imports-add')")
    public R save(@Validated({AddGroup.class}) @RequestBody SysExcelImportDTO sysExcelImportDTO) {
        return new R<>(sysExcelImportService.saveModelByDTO(sysExcelImportDTO));
    }

    /**
     * 修改记录
     *
     * @param sysExcelImportDTO excel导入DTO
     * @return R
     */
    @SysLog("修改excel导入")
    @PutMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('upms-excel-imports-edit')")
    public R update(@PathVariable("id") String id, @Validated({UpdateGroup.class}) @RequestBody SysExcelImportDTO sysExcelImportDTO) {
        sysExcelImportService.modModelByDTO(sysExcelImportDTO);
        return new R<>();
    }

    /**
     * 通过id删除一条记录
     *
     * @param id 主键
     * @return R
     */
    @SysLog("删除excel导入")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('upms-excel-imports-del')")
    public R removeById(@PathVariable String id) {
        sysExcelImportService.deleteByPrimaryKey(id);
        return new R<>();
    }

    /**
     * 批量记录
     *
     * @param ids 主键
     * @return R
     */
    @SysLog("批量删除excel导入")
    @DeleteMapping("")
    @PreAuthorize("@pms.hasPermission('upms-excel-imports-del')")
    public R removeIds(@RequestBody List<String> ids) {
        sysExcelImportService.batchDelete(ids);
        return new R<>();
    }

    /**
     * 获取分页
     *
     * @param pageNum           当前页码
     * @param pageSize          每页条数
     * @param sysExcelImportDTO excel导入DTO
     * @return R
     */
    @GetMapping("/page")
    public R<AbstractPageResultBean<SysExcelImport>> query(SysExcelImportDTO sysExcelImportDTO, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
        return new R<>(sysExcelImportService.selectPageInfo(sysExcelImportDTO, pageNum, pageSize));
    }

    /**
     * 获取列表
     *
     * @param sysExcelImportDTO excel导入DTO
     * @return R
     */
    @GetMapping("")
    public R query(SysExcelImportDTO sysExcelImportDTO) {
        return new R<>(sysExcelImportService.getModelListByDTO(sysExcelImportDTO));
    }

    /**
     * excel导入导出
     *
     * @param sysExcelImportDTO excel导入DTO
     * @return R
     */
    @GetMapping("/export")
    @SysLog("excel导入导出")
    @PreAuthorize("@pms.hasPermission('upms-excel-imports-export')")
    public void export(HttpServletResponse response, SysExcelImportDTO sysExcelImportDTO) {
        List<SysExcelImport> list = sysExcelImportService.getModelListByDTO(sysExcelImportDTO);
        ExcelUtil.exportResponseDict(response, ExportSysExcelImportVO.class, BeanConverterUtil.copyListProperties(list, ExportSysExcelImportVO.class), "excel导入");
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return :
     */
    @PostMapping("/import")
    @SneakyThrows
    public R doUpload(@RequestParam("file") MultipartFile file, @RequestParam("conditionInfo") String conditionInfo,
                      @RequestParam("type") Integer type, @RequestParam(value = "name", required = false) String name) {
        if (file.isEmpty()) {
            return R.error("请选择一个上传文件");
        }

        String fileFullName = file.getOriginalFilename();
        SysExcelImportDTO excelImportDTO = new SysExcelImportDTO();
        excelImportDTO.setType(type);
        excelImportDTO.setConditionInfo(conditionInfo);
        List<SysExcelImport> list = sysExcelImportService.getModelListByDTO(excelImportDTO);
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException(ResultCode.YEAR_FILE_EXIST_DELETE_BEFORE);
        }

        excelImportDTO.setName(StringUtils.isEmpty(name) ? fileFullName : name);
        int endIndex = fileFullName.lastIndexOf(".");
//        String fileType = fileFullName.substring(endIndex);
//        if (!XSSF.equals(fileType)) {
//            throw new BusinessException(ResultCode.FILE_TYPE_INVALID);
//        }
        String uuid = IdGeneratorUtils.getObjectId();
        String path = CommonConstants.RESOURCE_PREFIX + "/excel/" + DateUtil.formatDate(new Date()) + "/" + uuid + "/";
        String filePath = UPLOAD_ROOT_FOLDER + path;
        excelImportDTO.setUrl(path + fileFullName);
        try {
            FileUtils.uploadFile(file.getBytes(), filePath, fileFullName);
        } catch (Exception e) {
            throw new Exception("上传文件失败：" + e.getMessage());
        }
        String htmlName = uuid + ".html";
        String htmlUrl = path + htmlName;
        String htmlPath = filePath + htmlName;
        try {
            ExcelToHtml.create(file.getInputStream(), htmlPath);
        } catch (Exception e) {
            throw new Exception("文件转html失败：" + e.getMessage());
        }
        excelImportDTO.setHtmlUrl(htmlUrl);
        sysExcelImportService.saveModelByDTO(excelImportDTO);
        return R.success(ResultCode.SUCCESS);
    }

}
